import { useContext, useState } from 'react';
import { Button, InputNumber, List, Typography, Image } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import React from 'react';
import { ConfigContext } from '../../configProvider';
import './index.less';
interface CartItem {
  id: number;
  name: string;
  price: number;
  quantity: number;
  maxQuantity?: number;
  imageSrc?: string;
}

interface Props {
  items: CartItem[];
  onItemQuantityChange: (id: number, quantity: number) => void;
  onItemRemove: (id: number) => void;
  title?: string;
  hasImage?: boolean;
}

const ShoppingCart: React.FC<Props> = ({
  items,
  onItemQuantityChange,
  onItemRemove,
  title,
  hasImage,
}) => {
  const { prefix } = useContext(ConfigContext);
  const pf = prefix + '-cart';

  const getTotal = () => items.reduce((acc, item) => acc + item.price * item.quantity, 0);
  const [total, setTotal] = useState<number>(getTotal());
  const handleQuantityChange = (id: number, quantity: number) => {
    if (onItemQuantityChange) {
      onItemQuantityChange(id, quantity);
    }
    setTotal(getTotal());
  };

  const handleRemoveClick = (id: number) => {
    if (onItemRemove) {
      onItemRemove(id);
    }
    setTotal(getTotal());
  };
  setTimeout(() => setTotal(getTotal()), 200);
  return (
    <div className={pf}>
      <Typography.Title level={2}>{title ? title : 'Shopping Cart'}</Typography.Title>
      <List
        dataSource={items}
        renderItem={(item) => (
          <List.Item
            actions={[
              <Button
                type="text"
                icon={<DeleteOutlined />}
                onClick={() => handleRemoveClick(item.id)}
              />,
            ]}
            className={`${pf}-list-item`}
          >
            {hasImage ? (
              <Image src={item.imageSrc} height="5em" className={`${pf}-item-img`} />
            ) : null}
            <List.Item.Meta title={item.name} />
            <InputNumber
              min={1}
              max={item.maxQuantity}
              value={item.quantity}
              onChange={(value) => handleQuantityChange(item.id, value as number)}
            />
            <Typography.Text strong className={`${pf}-price`}>
              {`$${(item.price * item.quantity).toFixed(2)}`}
            </Typography.Text>
          </List.Item>
        )}
      />
      <Typography.Title level={4} className={`${pf}-total-price`}>{`Total: $${total.toFixed(
        2,
      )}`}</Typography.Title>
    </div>
  );
};

export default ShoppingCart;
